package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    //@Value("${userregister.password.rule}")
    private String rule = "^[\\w]{6,18}$";

    @Autowired
    private ApUserRealnameMapper userRealnameMapper;


    /**
     * app端登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {

        //int a = 1/0;
//        if(true){
//            throw new CustomException(AppHttpCodeEnum.NEED_ADMIND);
//        }

        //1.正常登录（手机号和密码）
        if(StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            //1.1 查询当前用户  根据手机号查询
            ApUser dbUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if(dbUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }



            //1.2 校验密码是否正确
            String salt = dbUser.getSalt();
            String password = dto.getPassword();
            password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if(!dbUser.getPassword().equals(password)){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //1.3 返回token
            Map<String,Object> map = new HashMap<>();
            dbUser.setSalt("");
            dbUser.setPassword("");
            map.put("user",dbUser);
            map.put("token", AppJwtUtil.getToken(dbUser.getId().longValue()));

            return ResponseResult.okResult(map);


        }else {
            //补充登录逻辑
            if (StringUtils.isNotEmpty(dto.getPhone())) {
                ApUser dbUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
                if (dbUser != null) {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
                }
            }
            //2.游客登录  token  使用0生成
            Map<String,Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }

    }

    /**
     * 用户注册
     *
     * @param apUser
     * @return
     */
    @Override
    public ResponseResult register(ApUser apUser) {
        //验证手机号是否非注册
        ApUser one = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, apUser.getPhone()));
        if (one!=null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"手机号已注册");

        //判断密码规则与手机号规则
        if (!apUser.getPassword().matches(rule))
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"密码不符合6-18位哦");
        if (!apUser.getPhone().matches("^[1][0-9]{10}$"))
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"您的手机号不符合规则哦");

        //完善apUser完成注册,返回401
        String replace = UUID.randomUUID().toString().replace("-", "");
        apUser.setSalt(replace);
        apUser.setPassword(DigestUtils.md5DigestAsHex((apUser.getPassword()+replace).getBytes()));
        apUser.setName("快更换一个你喜欢的名字吧");

        boolean save = save(apUser);
        //创建自媒体审核数据
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setUserId(apUser.getId());
        apUserRealname.setStatus(0);
        userRealnameMapper.insert(apUserRealname);

        return ResponseResult.okResult("注册成功");
    }
}
